﻿const { app, BrowserWindow, globalShortcut, ipcMain } = require("electron");
const path = require("path");
const { argv } = require("process");
const DataManager = require("./app_modules/DataManager");
const logger = require('./app_modules/Logger').getLogger('app');
const { screenImgPath } = require('./app_modules/filePath')
const { imgToWebp } = require('./app_modules/fileUtils')
const fs = require('fs')
let win = null;
let photoWin = null
const { ossAiRequest } = require('./app_modules/ossAi')
const { uploadAndDownloadFile } = require('./app_modules/ossUpload')
app.allowRendererProcessReuse = true;
app.commandLine.appendSwitch("autoplay-policy", "no-user-gesture-required");
app.commandLine.appendSwitch("touch-events", "enabled");

if (!app.requestSingleInstanceLock()) {
    //只允许启动一次
    app.quit();
} else {
    app.on("second-instance", (event, commandLine, workingDirectory) => {
        // 当运行第二个实例时,将会聚焦到myWindow这个窗口
        if (win) {
            win.show();
            if (win.isMinimized()) {
                win.restore();
            }
            win.focus();
        }
    });

    app.on("ready", function () {
        createWindowPhoto()
        if (argv[2] === "dev") {
            createWindow();
        } else {
            const Register = require("./app_modules/Register");
            Register.Judge(createWindow);
        }
        // 快捷键开启开发工具
        globalShortcut.register("CommandOrControl+Alt+`", function () {
            const focusWindow = BrowserWindow.getFocusedWindow();
            if (focusWindow) {
                focusWindow.webContents.openDevTools();
            }
        });

        globalShortcut.register("ESC", quitApplication);
    });
}

function createWindowPhoto(url) {
    photoWin = new BrowserWindow({
        width: 102 * 3, // 540
        height: 152 * 3, // 960
        // fullscreen: true,
        frame: false,
        webPreferences: {
            preload: path.join(__dirname, "app_modules/Font.js"),
            webSecurity: false,
        },
        show: false,
    });

    // photoWin.loadURL(__dirname + `/app_pages/build/index.html?url=${url}`);
    // if (argv[2] === "dev") {
    //     photoWin.loadURL(__dirname + `/app_pages/build/index.html?url=${url}`);
    //     if (argv[3] === "l") {
    //         photoWin.loadURL(`http://localhost:3000/?url=${url}`);
    //     }
    //     // win.webContents.openDevTools();

    // } else {
    //     photoWin.focus();
    //     // photoWin.setAlwaysOnTop(true, "screen-saver");
    // }
    // 图片加载完成后打印
    ipcMain.on("printLoad", (event, url) => {
        photoWin.webContents.print({
            scaleFactor: 100,
            silent: true,
            margins: {
                marginType: 'custom', // 设置边距为 0
                left: 0,
                right: 0,
                top: 0,
                bottom: 0,
            }
            // pageSize,
        }, (success, errorType) => {
            // console.log(pageSize, 'pageSize====');

            if (!success) {
                console.error(`打印失败: ${errorType}`);
            } else {
                console.log('打印成功');
            }
            photoWin?.hide();
        });
    })
}

function createWindow() {
    const { screen } = require("electron");
    const {
        id,
        bounds: { width, height },
    } = screen.getPrimaryDisplay();
    win = new BrowserWindow({
        ...(argv[3] !== "l" && argv[2] !== 'pro'
            ? {
                width: width,
                height: height,
                minWidth: width,
                minHeight: height,
                maxWidth: width,
                maxHeight: height,
                resizable: false,
                fullscreen: true,
                frame: false,
            }
            : {
                width: 1080 * 0.5,
                height: 1920 * 0.5,
                resizable: true,
                fullscreen: false,
                frame: true,
                // frame: false,
            }),

        webPreferences: {
            preload: path.join(__dirname, "app_modules/Font.js"),
            webSecurity: false,
        },
    });

    win.loadURL(__dirname + "/app_pages/build/index.html");
    if (argv[2] === "dev") {
        win.loadURL(__dirname + "/app_pages/build/index.html");
        if (argv[3] === "l") {
            win.loadURL("http://localhost:3000/");
        }
        // win.webContents.openDevTools();
    } else {
        win.focus();
        win.setAlwaysOnTop(true, "screen-saver");
    }
    win.on("close", quitApplication);
    ipcMain.on("photo", async (e, data) => {
        try {
            const fanPath = await DataManager.savePhoto(data)
            const res = await ossAiRequest(fanPath)
            const imageURL = res?.body?.data?.imageURL
            if (!imageURL) {
                logger.error('生成失败res')
            }
            win.webContents.send("photo", res?.body?.data?.imageURL);
        } catch (error) {
            win.webContents.send("photo", false);
            // win.webContents.send("message", '生成失败');
            logger.error('生成失败', error)
        }
    });
    /*  */
    ipcMain.on('screen', async (e, data) => {
        // 截取整个屏幕

        const image = await win.webContents.capturePage();
        fs.writeFileSync(screenImgPath, image.toPNG());

        uploadAndDownloadFile(screenImgPath).then((res) => {
            win.webContents.send("screen", res);
        })

    })

    ipcMain.on("print", (e, data) => {
        if (data?.imgUrl) {
            photoWin.show(); // 显示窗口
            const url = data?.imgUrl
            // 加载图片
            photoWin.loadURL(__dirname + `/app_pages/build/index.html?url=${url}`);
            if (argv[2] === "dev") {
                photoWin.loadURL(__dirname + `/app_pages/build/index.html?url=${url}`);
                if (argv[3] === "l") {
                    photoWin.loadURL(`http://localhost:3000/?url=${url}`);
                }
                // win.webContents.openDevTools();

            } else {
                photoWin.focus();
                // photoWin.setAlwaysOnTop(true, "screen-saver");
            }
        }
    })
    require("./app_modules/SignOut").in(win);
    const Server = require("./app_modules/Server");
    const download = require("./app_modules/DownloadManager");
    download.on("update", () => {
        if (win) win.reload();
    });
    Server.on("update", ({ id, serverip }) => {
        serverip = "http://" + serverip + "/";
        DataManager.setConfig("deviceId", id);
        DataManager.setConfig("serverHost", serverip);
        download.start(id, serverip);
    });
}

function quitApplication() {
    if (win) {
        win.hide();
    }
    win = null;
    setTimeout(function () {
        app.quit();
    }, 100);
}
